//
//  PersonInfoViewController.m
//  觅影
//
//  Created by  陶虹 on 16/4/10.
//  Copyright © 2016年  陶虹. All rights reserved.
//

#import "PersonInfoViewController.h"
#import "PersonInfoNoteBookModel.h"
#import "personInfoTableViewCell.h"
#import "PersonInfoAlbumModel.h"
#import "PersonInfoAlbumCell.h"
#import "PersonInfoAlbumHeader.h"
#import "PersonInfoAlbumFooter.h"

@interface PersonInfoViewController ()<UITableViewDataSource, UITableViewDelegate, UICollectionViewDataSource, UICollectionViewDelegate, UICollectionViewDelegateFlowLayout>
@property (strong, nonatomic) IBOutlet UIImageView *icon;
@property (strong, nonatomic) IBOutlet UILabel *nameLabel;
@property (strong, nonatomic) IBOutlet UILabel *watchedNumLabel;
@property (strong, nonatomic) IBOutlet UILabel *wantNumLabel;
@property (strong, nonatomic) IBOutlet UIButton *addButton;
@property (strong, nonatomic) IBOutlet UIButton *hisWatchedButton;
@property (strong, nonatomic) IBOutlet UIButton *hisAlbumButton;
@property (strong, nonatomic) IBOutlet UICollectionView *collectionView;
@property (strong, nonatomic) IBOutlet UITableView *tableView;
@property (strong, nonatomic) IBOutlet UILabel *label;
@property (nonatomic, strong) NSMutableArray *noteBookModelArray;
@property (nonatomic, strong) NSMutableArray *albumModelArray;
@property (nonatomic, strong) NSString *watchedNumStr;
@property (nonatomic, assign) NSInteger startPage;

@property (nonatomic, strong) NSString *watch_num;
@property (nonatomic, strong) NSString *want_num;
@property (nonatomic, strong) NSNumber *is_friend;
@end

@implementation PersonInfoViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    [self putUpView];
    [self netRequest];
    [self noteBookNetRequest];
    [self albumNetRequest];
    
    // 签协议
    [[EaseMob sharedInstance].chatManager addDelegate:(id)self delegateQueue:dispatch_get_main_queue()];
    
}

// 加别人为好友
//- (IBAction)addFriendsButton:(id)sender {
//    BOOL isSuccess = [EaseMob sharedInstance].chatManager addBuddy:@"" message:<#(NSString *)#> error:<#(EMError *__autoreleasing *)#>
//}

- (void)putUpView{
    self.label.hidden = YES;
    
    self.startPage = 1;
    self.edgesForExtendedLayout = NO;
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    [self.tableView registerNib:[UINib nibWithNibName:@"personInfoTableViewCell" bundle:nil] forCellReuseIdentifier:@"noteBookCell"];
    // 告诉系统 采用系统自动返回的高度
    self.tableView.rowHeight = UITableViewAutomaticDimension;
    // 预设高度
    self.tableView.estimatedRowHeight = 10;
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    self.tableView.mj_footer = [MJRefreshAutoFooter footerWithRefreshingBlock:^{
        [self noteBookNetRequestMore];
    }];
    
    [self.icon sd_setImageWithURL:[NSURL URLWithString:self.header]];
    self.nameLabel.text = self.username;
    
    self.collectionView.delegate = self;
    self.collectionView.dataSource = self;
    [self.collectionView registerNib:[UINib nibWithNibName:@"PersonInfoAlbumCell" bundle:nil] forCellWithReuseIdentifier:@"albumCell"];
    [self.collectionView registerNib:[UINib nibWithNibName:@"PersonInfoAlbumHeader" bundle:nil] forSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"albumHeader"];
    [self.collectionView registerNib:[UINib nibWithNibName:@"PersonInfoAlbumFooter" bundle:nil] forSupplementaryViewOfKind:UICollectionElementKindSectionFooter withReuseIdentifier:@"albumFooter"];
    self.collectionView.hidden = YES;
    self.collectionView.mj_footer = [MJRefreshAutoFooter footerWithRefreshingBlock:^{
        [self albumNetRequestMore];
    }];
    
}

- (void)netRequest{
    [RequestManager requestWithUrl:[NSString stringWithFormat:@"http://static.v6v7.com/snowman_api/user/userinfo_simple?uid=%@", self.uid] requestType:RequestTypeGET parDic:nil finshed:^(NSData *data) {
        NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
        NSDictionary *resultDic = dic[@"result"];
        self.is_friend = resultDic[@"is_friend"];
        self.want_num = resultDic[@"want_num"];
        self.watch_num = resultDic[@"watch_num"];
        dispatch_async(dispatch_get_main_queue(), ^{
            self.wantNumLabel.text = [NSString stringWithFormat:@"想看电影：%@ 部", self.want_num];
            self.watchedNumLabel.text = [NSString stringWithFormat:@"观影总数：%@ 部", self.watch_num];
        });
    } error:^(NSError *error) {
        NSLog(@"个人信息主界面数据请求失败");
    }];
}

- (void)noteBookNetRequest{
    self.noteBookModelArray = [NSMutableArray array];
    [RequestManager requestWithUrl:[NSString stringWithFormat:@"http://static.v6v7.com/snowman_api/movie_traces/list_by_time?page=1&page_size=10&uid=%@", self.uid] requestType:RequestTypeGET parDic:nil finshed:^(NSData *data) {
        NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
        NSArray *dataArray = dic[@"result"][@"data"];
        for (NSDictionary *dataDic in dataArray) {
            PersonInfoNoteBookModel *model = [[PersonInfoNoteBookModel alloc] init];
            [model setValuesForKeysWithDictionary:dataDic];
            [self.noteBookModelArray addObject:model];
        }
        dispatch_async(dispatch_get_main_queue(), ^{
            [self.tableView reloadData];
            if (self.noteBookModelArray.count == 0) {
                self.label.hidden = NO;
            }
        });
    } error:^(NSError *error) {
        NSLog(@"他的影记请求数据失败");
    }];
}

// noteBook的 tableView上拉加载
- (void)noteBookNetRequestMore{
    self.startPage++;
    self.noteBookModelArray = [NSMutableArray array];
    [RequestManager requestWithUrl:[NSString stringWithFormat:@"http://static.v6v7.com/snowman_api/movie_traces/list_by_time?page=%ld&page_size=10&uid=%@", self.startPage, self.uid] requestType:RequestTypeGET parDic:nil finshed:^(NSData *data) {
        NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
        NSArray *dataArray = dic[@"result"][@"data"];
        for (NSDictionary *dataDic in dataArray) {
            PersonInfoNoteBookModel *model = [[PersonInfoNoteBookModel alloc] init];
            [model setValuesForKeysWithDictionary:dataDic];
            [self.noteBookModelArray addObject:model];
        }
        dispatch_async(dispatch_get_main_queue(), ^{
            [self.tableView reloadData];
            if (self.noteBookModelArray.count == 0) {
                self.label.hidden = NO;
            }
            [self.tableView.mj_footer endRefreshing];
        });
    } error:^(NSError *error) {
        NSLog(@"他的影记上拉加载请求数据失败");
    }];
}

- (IBAction)hisNoteBookButtonAction:(id)sender {
    self.collectionView.hidden = YES;
    self.tableView.hidden = NO;
    if (self.noteBookModelArray.count == 0) {
        self.label.hidden = NO;
    }else{
        self.label.hidden = YES;
    }
}
- (IBAction)hisAlbumButtonAction:(id)sender {
    self.collectionView.hidden = NO;
    self.tableView.hidden = YES;
    if (self.albumModelArray.count == 0) {
        self.label.hidden = NO;
    }else{
        self.label.hidden = YES;
    }
}

- (void)albumNetRequest{
    self.albumModelArray = [NSMutableArray array];
    [RequestManager requestWithUrl:[ NSString stringWithFormat:@"http://static.v6v7.com/snowman_api/movie_traces/user_album_list?page=1&page_size=10&uid=%@", self.uid] requestType:RequestTypeGET parDic:nil finshed:^(NSData *data) {
        NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
        NSArray *dataArray = dic[@"result"][@"data"];
        for (NSDictionary *dataDic in dataArray) {
            PersonInfoAlbumModel *model = [[PersonInfoAlbumModel alloc] init];
            [model setValuesForKeysWithDictionary:dataDic];
            [self.albumModelArray addObject:model];
            
            NSArray *posterArray = dataDic[@"poster_list"];
            model.posterArray = [NSMutableArray array];
            for (NSString *posterStr in posterArray) {
                [model.posterArray addObject:posterStr];
            }
        }
        dispatch_async(dispatch_get_main_queue(), ^{
            [self.collectionView reloadData];
        });
    } error:^(NSError *error) {
        NSLog(@"他的专辑请求数据失败");
    }];
}
// album的 collectionView上拉加载
- (void)albumNetRequestMore{
    self.startPage++;
    self.albumModelArray = [NSMutableArray array];
    [RequestManager requestWithUrl:[ NSString stringWithFormat:@"http://static.v6v7.com/snowman_api/movie_traces/user_album_list?page=%ld&page_size=10&uid=%@", self.startPage, self.uid] requestType:RequestTypeGET parDic:nil finshed:^(NSData *data) {
        NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
        NSArray *dataArray = dic[@"result"][@"data"];
        for (NSDictionary *dataDic in dataArray) {
            PersonInfoAlbumModel *model = [[PersonInfoAlbumModel alloc] init];
            [model setValuesForKeysWithDictionary:dataDic];
            [self.albumModelArray addObject:model];
            
            NSArray *posterArray = dataDic[@"poster_list"];
            model.posterArray = [NSMutableArray array];
            [model.posterArray addObjectsFromArray:posterArray];
        }
        dispatch_async(dispatch_get_main_queue(), ^{
            [self.collectionView reloadData];
            [self.collectionView.mj_footer endRefreshing];
        });
    } error:^(NSError *error) {
        NSLog(@"他的专辑上拉加载请求数据失败");
    }];
}

#pragma mark --- collecitonView代理方法 ---
- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView{
    NSLog(@"%ld", self.albumModelArray.count);
    return self.albumModelArray.count;
}
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{
    PersonInfoAlbumModel *model = self.albumModelArray[section];
    return model.posterArray.count;
}
// 返回item
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
    PersonInfoAlbumModel *model = self.albumModelArray[indexPath.section];
    PersonInfoAlbumCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"albumCell" forIndexPath:indexPath];
    [cell.movieButton setImage:[UIImage imageWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:model.posterArray[indexPath.row]]]] forState:UIControlStateNormal];
    return cell;
}
// 返回header footer
- (UICollectionReusableView *)collectionView:(UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath{
    PersonInfoAlbumModel *model = self.albumModelArray[indexPath.section];
    UICollectionReusableView *reusableView = nil;
    if (kind == UICollectionElementKindSectionHeader) {
        PersonInfoAlbumHeader *header = [collectionView dequeueReusableSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"albumHeader" forIndexPath:indexPath];
        header.titleLabel.text = model.title;
        return header;
    }else if (kind == UICollectionElementKindSectionFooter){
        PersonInfoAlbumFooter *footer = [collectionView dequeueReusableSupplementaryViewOfKind:UICollectionElementKindSectionFooter withReuseIdentifier:@"albumFooter" forIndexPath:indexPath];
        footer.descLabel.text = model.desc;
        return footer;
    }
    return reusableView;
}
// header大小
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout referenceSizeForHeaderInSection:(NSInteger)section{
    return CGSizeMake(KWIDTH, 60);
}
// item大小
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath{
    return CGSizeMake((KWIDTH - 70) / 4, (KWIDTH - 70) / 4 * 92 / 67);
}
// 整体边距
- (UIEdgeInsets)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout insetForSectionAtIndex:(NSInteger)section{
    return UIEdgeInsetsMake(0, 20, 0, 20);
}
// 列边距
- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout minimumInteritemSpacingForSectionAtIndex:(NSInteger)section{
    return 10;
}

#pragma mark --- tableView代理方法 ---
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return self.noteBookModelArray.count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    personInfoTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"noteBookCell" forIndexPath:indexPath];
    PersonInfoNoteBookModel *model = self.noteBookModelArray[indexPath.row];
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    [cell configureCellWithModel:model];
    
    if (self.noteBookModelArray.count == 0) {
        self.label.hidden = NO;
    }
    return cell;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
